﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Stardust.Common.Utils
{
    public class MutilElapseTimer
    {
        private Timer _timer;
        private int _maxCount = int.MaxValue - 1;
        private Dictionary<int, HashSet<Action>> _jobs;
        public MutilElapseTimer()
        {
            _timer = new Timer(1000);
            _jobs = new Dictionary<int, HashSet<Action>>();

            _timer.Elapsed += _timer_Elapsed;
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _maxCount += 1;
            foreach (var item in _jobs.Where(kv => _maxCount % kv.Key == 0))
            {
                foreach (var action in item.Value)
                {
                    Task.Run(action);
                }
            }

            if (_maxCount >= int.MaxValue)
            {
                _maxCount = 0;
            }
        }

        public void AddJob(int seconds, Action action)
        {
            HashSet<Action> actionSet;
            if (!_jobs.TryGetValue(seconds, out actionSet))
            {
                actionSet = new HashSet<Action>();
                _jobs[seconds] = actionSet;
            }
            actionSet.Add(action);
        }

        public void Start()
        {
            _timer.Start();
        }
    }
}
